package com.cblz.bd.server.core.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import com.cblz.bd.common.core.constant.BdAdminConstant;
import com.cblz.bd.common.core.constant.ResponseStatusCode;
import com.cblz.bd.common.core.entity.BaAdminGroup;
import com.cblz.bd.common.core.entity.system.AdminGroupTree;
import com.cblz.bd.common.core.entity.system.IndexSearchParams;
import com.cblz.bd.common.core.exception.BdAdminException;
import com.cblz.bd.common.core.utils.ResultResponse;
import com.cblz.bd.common.core.utils.SearchParamsUtil;
import com.cblz.bd.server.core.annotation.AdminApiController;
import com.cblz.bd.server.core.entity.vo.BaAdminGroupVO;
import com.cblz.bd.server.core.service.BaAdminGroupService;
import io.vavr.Tuple4;
import io.vavr.control.Option;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * {@code @Name:} BaAdminGroupController
 * {@code @Description: }
 * {@code @Author:} by yanjieping
 * {@code @CreateDate:} 2022/11/14 - 周一
 */
@Slf4j
@RequiredArgsConstructor
@AdminApiController("group/admin")
public class BaAdminGroupController {

    private final BaAdminGroupService baAdminGroupService;

    /**
     * 查询信息
     *
     * @param searchParams 包含通用查询条件和分页参数
     *                     例： search[]: {"field":"id","val":"1","operator":"LIKE"}
     *                     page: 1
     * @return
     */
    @PostMapping("index")
    public ResultResponse listTree(@RequestBody(required = false) Map<String, Object> searchParams) throws Exception {
        Tuple4 paramsHandle = SearchParamsUtil.searchParamsHandle(searchParams);
        var search = (List<LinkedHashMap<String, Object>>) paramsHandle._1;
        var quickSearch = (Map<String, String>) paramsHandle._4;

        BaAdminGroup baAdminGroup = SearchParamsUtil.ParamsFormat2Class(new BaAdminGroup(), search, quickSearch);
        List<AdminGroupTree> groupInfoTree = baAdminGroupService.getAllGroupInfoTree(baAdminGroup);

        HashMap<String, Object> resultMap = new HashMap<>();
        resultMap.put("list", groupInfoTree);
        // 查询当前登录用户不能操作的权限组
        resultMap.put("group", Option.of(baAdminGroupService.getBdAdminRulesByLoginId(Integer.valueOf(StpUtil.getLoginId().toString()))).getOrNull().stream().mapToInt(BaAdminGroup::getId).toArray());
        return new ResultResponse().data(resultMap);
    }

    /**
     * @return
     * @author small-h
     * @date 2022/11/16 11:54
     * @descripe 角色创建
     **/
    @PostMapping("add")
    public ResultResponse addGroup(@RequestBody BaAdminGroupVO baAdminGroupVO) {
        Boolean isHasName = baAdminGroupService.checkHasName(0, baAdminGroupVO.getName());
        if (isHasName == true) {
            return new ResultResponse().message(ResponseStatusCode.ERROR.getStatusCode(), "此角色名已存在，不允许重复添加");
        }
        baAdminGroupService.addOrUpdateGroup(baAdminGroupVO);
        return new ResultResponse().message("角色创建成功");
    }

    @GetMapping("remoteSelect")
    public ResultResponse remoteSelect(@RequestParam Map<String, Object> paramsData) {
        IndexSearchParams indexSearchParams = IndexSearchParams.Map2IndexSearch(paramsData);
        // 如果查询主键ID和值都不为空那么查询等于主键值的数据
        List<AdminGroupTree> allGroupInfoTree = baAdminGroupService.getAllGroupInfoTree(indexSearchParams);
        return new ResultResponse().data(Map.of("options", allGroupInfoTree));
    }

    /**
     * @param id
     * @return
     * @author small-h
     * @date 2022/11/16 11:54
     * @descripe 根据id获取角色组信息
     **/
    @GetMapping("edit")
    public ResultResponse getGroupById(@RequestParam Integer id) {
        BaAdminGroup adminGroup = Option.of(baAdminGroupService.getGroupById(id)).getOrElseThrow(() -> new BdAdminException("未找到ID为" + id + "的角色组"));

        return new ResultResponse().data(BeanUtil.copyProperties(adminGroup, BaAdminGroupVO.class).setRules(StringUtils.split(adminGroup.getRules(), BdAdminConstant.SYSTEM_COMMA.getVal())));
    }

    @PostMapping("edit")
    public ResultResponse editGroupSave(@RequestBody BaAdminGroupVO baAdminGroupVO) {
        //判断名字修改后是否与其他角色重名
        Boolean isHasName = baAdminGroupService.checkHasName(baAdminGroupVO.getId(), baAdminGroupVO.getName());
        if (isHasName == true) {
            return new ResultResponse().message(ResponseStatusCode.ERROR.getStatusCode(), "组别名称不允许与其他角色名重复！");
        }
        baAdminGroupService.addOrUpdateGroup(baAdminGroupVO);
        return new ResultResponse().message("角色修改成功");
    }

    /**
     * @param ids
     * @return
     * @author small-h
     * @date 2022/11/16 11:54
     * @descripe 根据id删除角色信息
     **/
    @DeleteMapping("del")
    public ResultResponse deleteGroupByIds(@RequestBody Map ids) {

        ArrayList<Integer> idsArrayList = (ArrayList<Integer>) ids.get("ids");
        Integer[] idsArray = idsArrayList.toArray(new Integer[0]);
        // 判断校验删除的数据
        HashMap<String, Object> checkGroupData = (HashMap<String, Object>) baAdminGroupService.checkDelete(idsArray);
        Boolean isAllow = (Boolean) checkGroupData.get("isAllow");
        if (isAllow == false) {
            return new ResultResponse().message(ResponseStatusCode.ERROR.getStatusCode(), (String) checkGroupData.get("msg"));
        }

        baAdminGroupService.removeByIds(idsArrayList);
        return new ResultResponse().message("角色删除成功");
    }
}
